package org.xmppbot.net.nio;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

/**
 * Encodes output string to bytes.
 *
 * @author Stanislav Panov
 * @author Bulat Nigmatullin
 */
class ProtocolEncoderImpl implements ProtocolEncoder {

    private static final Logger _logger = LoggerFactory.getLogger(ProtocolEncoderImpl.class);

    private static final Charset INPUTSTREAM_CHARSET = Charset.forName("UTF-8");

    private final AttributeKey ENCODER = new AttributeKey(this.getClass(), "encoder");

    @Override
    public void dispose(IoSession arg0) throws Exception {
        // omit it
    }

    @Override
    public void encode(IoSession session, Object o, ProtocolEncoderOutput out)
            throws Exception {
        CharsetEncoder encoder = (CharsetEncoder) session.getAttribute(ENCODER);
        if (encoder == null) {
            encoder = INPUTSTREAM_CHARSET.newEncoder();
            session.setAttribute(ENCODER, encoder);
        }
        String value = (String) o;
        IoBuffer buf = IoBuffer.allocate(value.length());
        buf.putString(value, encoder);
        buf.flip();
        out.write(buf);
    }
}
